home *** CD-ROM | disk | FTP | other *** search
- Path: hillres151.cc.purdue.edu!pacman
- From: pacman@hillres151.cc.purdue.edu (PacMan)
- Newsgroups: comp.lang.c
- Subject: Re: pointers and functions
- Date: 26 Mar 1996 11:01:48 GMT
- Organization: prohibited
- Message-ID: <4j8iqs$9n9@mozo.cc.purdue.edu>
- References: <4j6dol$58g@news.bu.edu>
- NNTP-Posting-Host: hillres151.cc.purdue.edu
-
- In article <4j6dol$58g@news.bu.edu>, wai yip <lachesis@bu.edu> wrote:
- >can someone help me find the bug in this program?
-
- I found one. I'm not saying I found all of them..
- >this is the file the program reads from:
-
- [which we didn't need so I snipped]
-
- >
- >and here is the part of the program:
- >
-
- [snip some..]
- >
- >mazeType *readMaze(char *fname);
- >int printMaze(mazeType *maze);
- >
- >
- >mazeType *readMaze(char *fname)
- >{
- >FILE *ifp;
- >char c,*Array=NULL;
- >int x=0;
- >mazeType Maze;
- ^^^^^^^^^^^^^^
- >mazeType *StructPtr=NULL;
-
- [snip some stuff that puts data into the Maze struct]
-
- >StructPtr=&Maze;
- >return (StructPtr);
- >}
-
- The problem is that Maze is a local variable. It only exists inside the
- function readMaze. When you return its address, readMaze is finished, and its
- local variables disappear, and the calling function is left with a pointer to
- some data that isn't there anymore. After that, anything can happen-- bus
- errors, segmentation faults, the end of the universe...
-
- What you can do to correct this is to have the calling function pass in the
- address of an already allocated mazeType, and fill it in, or make the
- variable Maze be external or static so that it will outlive the function
- call, or have it point to malloc'ed space. I can't decide which solution is
- best for you without studying your program in detail, and I'm not feeling
- up to doing that.
- --
- Alan Curry
- -----BEGIN GEEK CODE BLOCK-----
- Version: 3.1
- GCS d? s++:-- a--- C+++ UL++++ P+ L+++>++++ E--- W-- N++ o K? w--- O? M--
- V? PS+ PE+ Y+ PGP- t* 5++ X+++ R- tv++ b- DI- D++ G+++ !e h! r-->+++ y?
- ------END GEEK CODE BLOCK------
-